package com.xz.courseschedule.service.impl;

import com.xz.courseschedule.common.dto.CourseTypeDistributionDto;
import com.xz.courseschedule.common.dto.RoomUsageDto;
import com.xz.courseschedule.mapper.CourseMapper;
import com.xz.courseschedule.mapper.TimetableMapper;
import com.xz.courseschedule.service.DashboardService;
import com.xz.courseschedule.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private TimetableMapper timetableMapper;

    @Override
    public Result<List<CourseTypeDistributionDto>> getCourseTypeDistribution() {
        List<Map<String, Object>> rawData = courseMapper.getCourseTypeDistribution();
        List<CourseTypeDistributionDto> dtoList = rawData.stream()
                .map(item -> {
                    Object valueObj = item.get("value");
                    Long value = 0L;
                    if (valueObj instanceof Number) {
                        value = ((Number) valueObj).longValue();
                    }
                    return new CourseTypeDistributionDto((String) item.get("name"), value);
                })
                .collect(Collectors.toList());
        return Result.success(dtoList);
    }

    @Override
    public Result<RoomUsageDto> getRoomUsage() {
        List<Map<String, Object>> rawData = timetableMapper.getRoomUsageByTimeSlot();
        
        // 定义所有可能的时间段
        List<String> allTimeSlots = Arrays.asList("1-2节", "3-4节", "5-6节", "7-8节", "9-11节");
        List<Integer> values = new ArrayList<>();
        
        // 为每个时间段填充数据
        for (String timeSlot : allTimeSlots) {
            Integer count = rawData.stream()
                    .filter(item -> timeSlot.equals(item.get("time_period")))
                    .findFirst()
                    .map(item -> {
                        Object countObj = item.get("room_count");
                        if (countObj instanceof Number) {
                            return ((Number) countObj).intValue();
                        }
                        return 0;
                    })
                    .orElse(0);
            values.add(count);
        }
        
        RoomUsageDto dto = new RoomUsageDto(allTimeSlots, values);
        return Result.success(dto);
    }
}